﻿using UnityEngine;
using System;
using System.Collections.Generic;

public partial class CyberU
{
    #region Lock

    public static ILock<MousePriority> scrollLock = MouseLock();
    
    public enum MousePriority
    {
        Screen,   // 最高优先级
        Panel,    // 中等优先级
        Component // 最低优先级
    }

    public interface ILock<T> where T : Enum
    {
        bool IsAvailable(T key);
        bool Acquire(T key);
        void Release(T key);
    }

    public static ILock<MousePriority> MouseLock()
    {
        return new PriorityEnumLock<MousePriority>();
    }

    public static ILock<MousePriority> MouseLock(MousePriority priority)
    {
        return new PriorityEnumLock<MousePriority>();
    }

    // 可扩展：支持其他枚举类型的锁
    public static ILock<T> CreateLock<T>(T priority) where T : Enum
    {
        return new PriorityEnumLock<T>();
    }

    public class PriorityEnumLock<T> : ILock<T> where T : Enum
    {
        private T _currentLock;
        private bool _isLocked;

        public PriorityEnumLock()
        {
            _isLocked = false;
            // 默认值（第一个枚举项）
            var values = Enum.GetValues(typeof(T));
            if (values.Length > 0)
            {
                _currentLock = (T)values.GetValue(0);
            }
        }

        public bool IsAvailable(T key)
        {
            if (!_isLocked)
                return true;

            // 比较优先级：如果 key 的优先级高于当前持有的锁，则可用
            return Comparer<T>.Default.Compare(key, _currentLock) > 0;
        }

        public bool Acquire(T key)
        {
            if (!IsAvailable(key))
                return false;

            _currentLock = key;
            _isLocked = true;
            return true;
        }

        public void Release(T key)
        {
            if (_isLocked && Equals(_currentLock, key))
            {
                _isLocked = false;
            }
        }
    }

    #endregion
}